package com.major;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class MyTask implements Runnable {

    private Socket accept;

    public MyTask(Socket accept) {
        this.accept = accept;
    }

    @Override
    public void run() {

        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            inputStream = accept.getInputStream();

            StringBuilder req = new StringBuilder();
            int len;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf)) != -1) {
                req.append(new String(buf, 0, len));
                if (len < 1024) {
                    accept.shutdownInput();
                }
            }

            // 得到请求对象
            Request request = Request.buildRequest(req.toString());
            if (!"/favicon.ico".equals(request.getUrl())) {
                System.out.println("A ip :" + accept.getRemoteSocketAddress().toString().substring(1) + " is coming for:" + request.getUrl().substring(1));
            }

            // 拿到输出流
            outputStream = accept.getOutputStream();
            // 得到响应对象
            Response response = new Response();
            response.addHeader("GYS","LSS ZHY");
            response.addHeader("301", "GYS LMY LHR OJW CYJ");
            //response.setData("<h1>Hello World!  你好 世界！</h1>");
            response.setData(HttpUtil.getPage(request.getUrl()));


            response.write(outputStream);
            /*String url = req.toString().split("\r\n")[0].split(" ")[1].substring(1);
            String url = request.getUrl();

            outputStream = accept.getOutputStream();
            outputStream.write(HttpUtil.getResponse(HttpUtil.getPage(url)));*/

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (accept != null) {
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
